//
//  String+Extension.swift
//  HotNews
//
//  Created by YYY on 2017/10/27.
//  Copyright © 2017年 成品家（北京）网路科技有限公司. All rights reserved.
//

import Foundation

extension String
{
    //获取label的size
    func calculateLabelSize(fontSize: CGFloat, size: CGSize) -> CGSize
    {
        let dict = [NSAttributedStringKey.font: UIFont.systemFont(ofSize: fontSize)]
        let rect = (self as NSString).boundingRect(with: size, options: [.usesLineFragmentOrigin], attributes: dict, context: nil)
        return rect.size
    }
    
    //获取href中的链接和文本(正则表达式)
    func hrefLinkText() -> (link: String, text: String)?
    {
        //匹配项
        let pattern = "<a href=\"(.*?)\" .*?\">(.*?)</a>"
        //创建正则表达式,获得匹配结果
        guard let regx = try? NSRegularExpression(pattern: pattern, options: []),
              let result = regx.firstMatch(in: self, options: [], range: NSRange(location: 0, length: characters.count)) else
        {
            return nil
        }
        //获得链接
        let link = (self as NSString).substring(with: result.range(at: 1))
        //获得文本
        let text = (self as NSString).substring(with: result.range(at: 2))
        return (link, text)
    }
}
